package br.com.felix.fwt.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import br.com.felix.fwt.log.LoggerFactory;
import br.com.felix.fwt.servlet.exception.UpdateFormFieldsException;

public abstract class MultiPartForm extends Form {

	private static final long serialVersionUID = 6123081667787380700L;

	private static Logger logger = LoggerFactory.getLogger(MultiPartForm.class);
	
	List<FileItem> anexos;

	public MultiPartForm(){
		super(EncType.MULTIPART_FORM_DATA);
	}
	
	public List<FileItem> getAnexos(){
		return anexos;
	}
	
	public FileItem getAnexo(int index){
		if(index >= anexos.size())
			return null;
		return anexos.get(index);
	}
	
	public void addAnexo(FileItem anexo){
		if(anexos == null)
			anexos = new ArrayList<FileItem>();
		anexos.add(anexo);
	}
	
	public void clearAnexos(){
		if(anexos != null)
			anexos.clear();
	}

	@Override
	public String updateFormFields(HttpServletRequest request) throws UpdateFormFieldsException {
		String action = null;
		
		String contentType = request.getHeader("Content-type");
		if (contentType!=null && contentType.contains("multipart/form-data")){
			DiskFileItemFactory factory = new DiskFileItemFactory();
			File tempDirectory = getUploadTempDirectory();
	        factory.setRepository(tempDirectory);
			
			ServletFileUpload upload = new ServletFileUpload(factory);
			clearAnexos();
			try {
				List<?> /* FileItem */ items = upload.parseRequest(request);
				Iterator<?> iter = items.iterator();
				while (iter.hasNext()) {
				    FileItem item = (FileItem) iter.next();
				    String name = item.getFieldName();
				    if (item.isFormField()) {
				        String value = item.getString();
				        if(name.equals("actionName"))
				        	action = value;
				        updateComponentValue(name, value);
				        logger.debug("Processing Parameter...");
				        logger.debug("Name: " + name);
				        logger.debug("Value: " + value);
				    } 
				    else {
				    	if (item.getSize()>0){
					    	addAnexo(item);
					    	logger.debug("Processing attachment...");
					    	logger.debug("FieldName: " + name);
					    	logger.debug("FileName: " + item.getName());
					    	logger.debug("Content-Type: " + item.getContentType());
					    	logger.debug("SizeInBytes: " + item.getSize());
					    	updateComponentValue(name, new File(tempDirectory,item.getName()).getAbsolutePath());
				    	}
				    }
				}
			} catch (FileUploadException e) {
				String msg = "An error ocurred during file upload.";
				logger.error(msg,e);
				throw new UpdateFormFieldsException(msg,e);
			}
		}

		return action;
	}

	
	/**
	 * Specifies where uploaded files will be stored temporally.
	 * */
    protected abstract File getUploadTempDirectory();
	
	
}
